--select * into movimenti_old from movimenti
-- DROP TABLE FOGLIO
select M.CODPREN, M.N_MOD, M.N_SEQ INTO FOGLIO from movimenti m
	inner join biglietti b on m.codpren=b.codpren and m.n_mod=b.n_mod and m.n_seq=b.n_seq
 where m.DATA_EMISSIONE is null and b.CODBIGL is not null and m.tipomov='pp'

SELECT count(*) FROM FOGLIO 
 
-- SELECT * FROM MOVIMENTI WHERE CODPREN IN (select CODPREN from Foglio) AND TIPOMOV='PP'

 
DECLARE @CODPREN VARCHAR(14), @N_MOD INT, @N_SEQ INT
 DECLARE CURSORE CURSOR FOR SELECT CODPREN, N_MOD, N_SEQ FROM Foglio
 OPEN CURSORE
 FETCH NEXT FROM CURSORE INTO @CODPREN, @N_MOD, @N_SEQ
 WHILE @@FETCH_STATUS=0
 BEGIN
	
	--SELECT * FROM MOVIMENTI WHERE CODPREN=@CODPREN AND N_SEQ=@N_SEQ AND N_MOD=@N_MOD AND TIPOMOV='PP'
	UPDATE MOVIMENTI SET DATA_EMISSIONE=(SELECT DATA_EMISS FROM BIGLIETTI WHERE CODPREN=@CODPREN
		AND N_SEQ=@N_SEQ AND N_MOD=@N_MOD and riemesso=0) WHERE CODPREN=@CODPREN AND N_SEQ=@N_SEQ AND N_MOD=@N_MOD AND TIPOMOV='PP'
	FETCH NEXT FROM CURSORE INTO @CODPREN, @N_MOD, @N_SEQ
 END
 CLOSE CURSORE
 DEALLOCATE CURSORE
 
 
select count(*) from movimenti m
	inner join biglietti b on m.codpren=b.codpren and m.n_mod=b.n_mod and m.n_seq=b.n_seq
 where m.DATA_EMISSIONE is null and b.CODBIGL is not null and m.tipomov='pp'
 